class Solution {
    int m = 0;
    int n = 0;
    int[] start;
    int[] end;
    int ret = 0;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    boolean[][] check;
    int num = 0;
    int count = 0;
    public int uniquePathsIII(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        start = new int[2];
        end = new int[2];
        check = new boolean[m][n];
        // 先找到起始方格 和 终止方格
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(grid[i][j] == 1){
                    start[0] = i;
                    start[1] = j;
                }else if(grid[i][j] == 2){
                    end[0] = i;
                    end[1] = j;
                }else if(grid[i][j] == 0){
                    num++;
                }
            }
        }
        check[start[0]][start[1]] = true;
        dfs(grid, start[0], start[1]);
        return ret;
    }
    public void dfs(int[][] grid, int i, int j){
        if(i == end[0] && j == end[1]){
            if(count - 1 == num){
                ret++;
            }
            return;
        }
        for(int k = 0; k < 4; k++){
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && check[x][y] == false && (grid[x][y] == 0 || grid[x][y] == 2)){
                count++;
                check[x][y] = true;
                dfs(grid, x, y);
                count--;
                check[x][y] = false;
            }
        }
    }
}